<template>
  <el-dialog v-el-drag-dialog :title="type === 'add' ? '新增' : '编辑'" :visible.sync="visible" width="800px" @closed="reset">
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="150px">
      <el-form-item label="车牌号" prop="licensePlate">
        <el-input v-model.trim="temp.licensePlate" placeholder="请输入" clearable maxlength="10" />
      </el-form-item>
      <el-form-item label="司机" prop="driver">
        <el-input v-model.trim="temp.driver" placeholder="请输入" maxlength="10" clearable />
      </el-form-item>
      <el-form-item label="燃气类型" prop="purchaseType">
        <el-select v-model="temp.purchaseType" filterable clearable>
          <el-option v-for="(item, index) in purchaseTypeList" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="卸车前车辆毛重(kg)" prop="weightBefore">
        <el-input-number
          v-model.trim="temp.weightBefore"
          :controls="false"
          :min="0"
          :max="10000000"
          placeholder="请输入"
          clearable
          :precision="2"
          style="width: 100%;"
          @change="changeWeightBefore"
        />
      </el-form-item>
      <el-form-item label="卸车后车辆毛重(kg)" prop="weightAfter">
        <el-input-number
          v-model.trim="temp.weightAfter"
          :controls="false"
          :min="0"
          :max="10000000"
          placeholder="请输入"
          clearable
          :precision="2"
          style="width: 100%;"
          @change="changeWeightAfter"
        />
      </el-form-item>
      <el-form-item label="实际卸货量(kg)" prop="totalWeight">
        <el-input-number
          v-model.trim="temp.totalWeight"
          :disabled="true"
          :controls="false"
          :min="0"
          :max="10000000"
          placeholder="请输入"
          clearable
          :precision="2"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="出厂单价(kg/元)" prop="unitPrice">
        <el-input-number
          v-model.trim="temp.unitPrice"
          :controls="false"
          :min="0"
          :max="10000000"
          placeholder="请输入"
          clearable
          :precision="2"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="运费(kg/元)" prop="freight">
        <el-input-number
          v-model.trim="temp.freight"
          :controls="false"
          :min="0"
          :max="10000000"
          placeholder="请输入"
          clearable
          :precision="2"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="采购站点" prop="purchaseOrgSNNo">
        <el-tree-select
          v-model="temp.purchaseOrgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="采购日期" prop="purchaseDt">
        <el-date-picker
          v-model="temp.purchaseDt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item :table-form-merge="0.2">
        <el-checkbox v-model="temp.iscalculateFreight" style="margin-right: 20px;">算运费</el-checkbox>
      </el-form-item>
      <el-form-item label="上传图片" prop="" style="width: 100%;">
        <el-upload
          style="display: inline-block;"
          action="#"
          :data="fileQiniuData"
          list-type="picture-card"
          :limit="6"
          :before-upload="beforeUpload"
          accept=".bmp, .gif, .jpg, .jpeg, .png, image/bmp, image/gif, image/jpg, image/jpeg, image/png"
          :file-list="temp.attachmentInfoList"
          :http-request="uploadToQiNiu"
          :on-exceed="handleExceed"
          multiple
        >
          <i class="el-icon-plus" />
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="file.url">
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in" />
              </span>
              <span
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogImageVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="备注" prop="remark" class="block">
        <el-input v-model="temp.remark" type="textarea" :rows="2" show-word-limit maxlength="100" />
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import dayjs from 'dayjs'
  import { queryQiniuyunUploadToken, queryAttachList, purchaseUnloadingSave, purchaseUnloadingEdit } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { accSub, keepDotLength } from '@/utils/math'
  import * as qiniu from 'qiniu-js'
  // import watermark from '@/utils/watermark'
  import compress from '@/utils/compress'
  export default {
    name: 'add',
    props: {
      orgList: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        dialogImageVisible: false,
        dialogImageUrl: '',
        type: 'add',
        baseUrl: 'http://image.haoyunqi.com.cn/',
        treeData: [],
        fileQiniuData: {
          key: '',
          token: '',
          data: {},
          bucket: ' '
        },
        temp: {
          licensePlate: '',
          driver: '',
          purchaseType: '',
          weightBefore: '',
          weightAfter: '',
          totalWeight: '',
          unitPrice: '',
          freight: '',
          purchaseOrgId: '',
          purchaseOrgName: '',
          purchaseOrgSNNo: '',
          purchaseDt: '',
          iscalculateFreight: '',
          remark: '',
          attachmentInfoList: []
        },
        rules: {
          licensePlate: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
          purchaseType: [{ required: true, message: '请选择燃气类型', trigger: 'change' }],
          weightBefore: [{ required: true, message: '请输入卸车前重量', trigger: 'blur' }],
          weightAfter: [{ required: true, message: '请输入卸车后重量', trigger: 'blur' }],
          totalWeight: [{ required: true, message: '请输入卸车总重量', trigger: 'change' }],
          unitPrice: [{ required: true, message: '请输入出厂单价', trigger: 'blur' }],
          freight: [{ required: true, message: '请输入运费', trigger: 'blur' }],
          purchaseOrgSNNo: [{ required: true, message: '请选择采购站点', trigger: 'change' }],
          purchaseDt: [{ required: true, message: '请选择采购日期', trigger: 'change' }]
        },
        pickerOptionsYear: {
          disabledDate(time) {
            const currentYear = new Date().getFullYear()
            return time.getFullYear() > currentYear
          }
        },
        purchaseTypeList: [
          { label: '液化气', value: 1 },
          { label: '丙烷', value: 2 }
        ]
      }
    },
    computed: {
      // totalWeight() {
      //   // return this.data.weightBefore
      // }
    },
    methods: {
      open(temp) {
        return new Promise(async resolve => {
          this.resolve = resolve
          this.type = 'add'
          this.visible = true
          await this.getTreeData()
          await this.getQiniuyunUploadToken()
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
            this.temp.iscalculateFreight = temp.iscalculateFreight === 1
            this.temp.purchaseDt = dayjs(temp.purchaseDt).format('YYYY-MM-DD')
            // this.$refs.dataForm.clearValidate(['purchaseOrgSNNo','purchaseDt'])
            if (temp.picIds) {
              const res = await queryAttachList({ picIds: temp.picIds })
              this.temp.attachmentInfoList = res.data || []
            }
            this.type = 'edit'
          }
        })
      },
      success() {
        this.$refs.dataForm.validate(async valid => {
          if (!valid) return
          const params = {
            ...this.temp
          }
          // 1：是 2：否
          params.iscalculateFreight = params.iscalculateFreight ? 1 : 2
          // if (this.type === 'edit') {
          // } else {
          // }
          try {
            if (this.type === 'add') {
              this.add(params)
            } else {
              this.edit(params)
            }
          } catch (e) {
            // this.$message.error('银行卡号已存在,请查看是否启用')
          }
        })
      },
      async add(params) {
        await purchaseUnloadingSave(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit(params) {
        await purchaseUnloadingEdit(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.visible = false
        this.temp = {
          licensePlate: '',
          driver: '',
          purchaseType: '',
          weightBefore: '',
          weightAfter: '',
          totalWeight: '',
          unitPrice: '',
          freight: '',
          purchaseOrgId: '',
          purchaseOrgName: '',
          purchaseOrgSNNo: '',
          purchaseDt: '',
          iscalculateFreight: '',
          remark: '',
          attachmentInfoList: []
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.temp.purchaseOrgSNNo = value.orgSNNo
        this.temp.purchaseOrgId = value.orgId
        this.temp.purchaseOrgName = value.orgName
        // this.$nextTick(() => {
        //   this.$refs.lbTable.fetch({ currentPage: 1 })
        // })
      },
      changeWeightBefore(value) {
        this.temp.totalWeight = keepDotLength(accSub(value, this.temp.weightAfter), 2)
      },
      changeWeightAfter(value) {
        if (value > this.temp.weightBefore) {
          this.$message({
            showClose: true,
            message: '卸车后重量不得大于卸车前重量',
            type: 'warning'
          })
          this.$nextTick(() => {
            this.$set(this.temp, 'weightAfter', 0)
          })
          return
        }
        this.temp.totalWeight = keepDotLength(accSub(this.temp.weightBefore, value), 2)
      },
      beforeUpload(file) {
        const key = `${new Date().getTime()}_${file.name}`
        this.fileQiniuData.key = key
        return this.fileQiniuData
      },
      handleExceed(files, fileList) {
        this.$message.warning('最多只能上传六张照片')
      },
      // 获取七牛云上传token
      async getQiniuyunUploadToken() {
        const res = await queryQiniuyunUploadToken()
        this.fileQiniuData.token = res.data
        // this.token = res.data
        // if (this.temp.attachmentInfoList.length > 0) {
        //   this.temp.attachmentInfoList[0].qiniuData.token = this.token
        //   this.fileQiniuData.token = this.token
        // }
      },
      uploadToQiNiu(e) {
        const _this = this
        const file = e.file // Blob 对象，上传的文件
        const config = {
          useCdnDomain: true, // 表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
          region: qiniu.region.z0 // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域
        }
        const putExtra = {
          fname: this.fileQiniuData.key, // 文件原文件名
          params: {}, // 用来放置自定义变量
          mimeType: ['image/png', 'image/jpeg', 'image/jpg'] // 用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
        }
        this.changeFile(file, function(file) {
          console.log(file)
          var observable = qiniu.upload(file, _this.fileQiniuData.key, _this.fileQiniuData.token, putExtra, config)
          observable.subscribe({
            next: result => {
              // 主要用来展示进度
              // console.log(result)
            },
            error: errResult => {
              // 失败报错信息
              // console.log(errResult)
              _this.$message.error('上传失败')
              const length = _this.temp.attachmentInfoList.length
              _this.temp.attachmentInfoList.splice(length - 1, 1)
            },
            complete: result => {
              // 接收成功后返回的信息
              _this.temp.attachmentInfoList.push(result)
              _this.temp.attachmentInfoList[_this.temp.attachmentInfoList.length - 1].url = _this.baseUrl + result.key
              console.log('attachmentInfoList', _this.temp.attachmentInfoList)
            }
          })
        }, function() {
          _this.$message.error('压缩失败')
        })
      },
      changeFile(file, onload, onerror) {
        compress(file, 3 * 1024 * 1024, 2 * 1024 * 1024, onload
                 //  function (_file) {
                 //    watermark(_file, '仅供附件上传使用，他用无效',onload, onerror)
                 //  }
                 , onerror)
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogImageVisible = true
      },
      handleRemove(file) {
        console.log('removeFile', file)
        console.log('attachmentInfoList', this.temp.attachmentInfoList)
        this.temp.attachmentInfoList.forEach((item, index) => {
          if (item.uid === file.uid) {
            this.temp.attachmentInfoList.splice(index, 1)
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;

  & /deep/ .el-form-item {
    width: 50%;
  }

  .block {
    width: 100%;
  }
}
</style>
